package org.atlantis.sbe.random
import java.io.IOException
import java.net.ServerSocket
import java.net.Socket
import scala.actors.Actor
import scala.actors.Actor._
import scala.util.Random
import java.io.DataOutputStream
import java.io.ObjectInputStream
import java.io.DataInputStream
import java.net.SocketException

object RandomServer {

    def main(args: Array[String]) {
        try {
            val listener = new ServerSocket(9999)
            while (true) new Thread(new ServerThread(listener.accept())).start
            listener.close
        } catch {
            case e: IOException =>
                System.err.println("Could not listen on port: 9999")
                System.exit(-1)
        }
    }

    case class ServerThread(socket: Socket) extends Runnable {
        override def run(): Unit = {
            val rand = new Random(System.currentTimeMillis)
            try {
                val out = new DataOutputStream(socket.getOutputStream)
                val in = new ObjectInputStream(new DataInputStream(socket.getInputStream))
                val filter = in.readObject().asInstanceOf[Int => Boolean]
                while (true) {
                    var succeeded = false;
                    do {
                        val x = rand.nextInt(1000)
                        succeeded = filter(x)
                        if (succeeded) out.writeInt(x)
                    } while (!succeeded);
                    Thread.sleep(1000)
                }
                out.close
                in.close
                socket.close
            } catch {
                case e: SocketException => ()
                case e: IOException => e.printStackTrace
            }
        }
    }
}
